<template>
  <div class="app-container calendar-list-container">
    <router-link :to="{name:'hospital_list'}">
      <el-button type="primary" v-waves @click="disabled=false">返回</el-button>
    </router-link>
    <el-button type="primary" v-waves @click="roleLevel = 1" style="margin-left:10px;">编辑</el-button>
    <div style="margin:20px;">{{roleLevel == 1 ? '编辑医院':'医院详情' }}</div>
    <el-form
      style="width:600px"
      :rules="addRules"
      :model="addQuery"
      status-icon
      ref="addForm"
      label-width="150px"
      :disabled="roleLevel != 1"
    >
      <el-form-item label="医院名称" prop="hospitalName">
        <el-input
          type="text"
          v-model="addQuery.hospitalName"
          placeholder="请输入医院名称"
          auto-complete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="所在地区" required>
        <el-form-item required prop="province" style="display:inline-block">
          <el-select
            clearable
            style="width: 100px;"
            v-model="addQuery.province"
            placeholder="省"
            class="filter-item"
            @change="getCities(1)"
          >
            <el-option v-for="p in provices" :label="p.NAME" :value="p.AREA_ID" :key="p.AREA_ID"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="city" style="display:inline-block">
          <el-select
            clearable
            style="width: 100px;"
            v-model="addQuery.city"
            placeholder="市"
            class="filter-item"
            @change="getAreas(1)"
          >
            <el-option v-for="c in cities" :label="c.NAME" :value="c.AREA_ID" :key="c.AREA_ID"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="area" style="display:inline-block">
          <el-select
            clearable
            style="width: 120px;"
            v-model="addQuery.area"
            placeholder="区"
            class="filter-item"
          >
            <el-option v-for="a in areas" :label="a.NAME" :value="a.AREA_ID" :key="a.AREA_ID"/>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input type="textarea" v-model="addQuery.address" placeholder="请输入详细地址"></el-input>
      </el-form-item>
      <el-form-item label="押金金额" prop="deposit">
        <el-input type="text" v-model="addQuery.deposit" placeholder="请输入押金金额"></el-input>
      </el-form-item>
      <el-form-item label="管理员" prop="managerId" v-if="!visible">
        <el-row>
          <el-col :span="19">
            <el-input disabled type="text" v-model="addQuery.managerName"></el-input>
          </el-col>
          <el-col :span="5">
            <el-button type="success" v-waves style="display:inline-block;float:right;" @click="visible = true">重新选择</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item 
        v-if="visible"
        :label="item.label" 
        prop="" 
        v-for="(item,index) in managerList"
        :key=index
      >
        <el-select
          style="width: 100%;width:300px;margin-right:8px;"
          placeholder="请选择管理员"
          class="filter-item"
          v-model="item.managerName"
          @change="managerChange"
        >
          <el-option
            v-for="(item1,index1) in item.list"
            :label="item1.managerName"
            :value="item1.managerName"
            :key="index1"
          />
        </el-select>
        <el-button type="success" v-waves style="display:inline-block;" @click="setManagerId(item)">确定</el-button>
        <el-button type="warning" v-waves style="display:inline-block;" v-if="item.showNext"  @click="getManagerList(1)">下一级</el-button>
      </el-form-item>
      <el-form-item label="" prop="" v-show="tipText && visible">
        <span style="color:#888">{{tipText}}</span>
      </el-form-item>
      <el-form-item label="当前选择的代理商" prop="managerId" v-if="visible">
        <el-input type="text" v-model="nowManager.managerName" disabled></el-input>
      </el-form-item>
      <!-- <el-form-item label="管理员手机号">
        <el-input v-model="addQuery.managerPhone" disabled></el-input>
      </el-form-item>
      <el-form-item label="管理员等级">
        <el-input v-model="addQuery.managerLevel" disabled></el-input>
      </el-form-item>
      <el-form-item label="管理员分成比例">
        <el-input v-model="addQuery.managerCommissionRatio" disabled></el-input>
      </el-form-item> -->
    </el-form>
    <el-button v-if="roleLevel == 1 " size="small" type="primary" @click="submitForm">确定</el-button>
  </div>
</template>
<script>
import {
  getAddressByAreaId,
  getObjByName,
  getObjByAreaId
} from "@/utils/getAddress";
import { parseTime } from "@/utils";
import pcq from "@/components/index";
import {
  getHospitalList,
  managerList,
  setHospital
} from "@/api/hospital";
export default {
  name: "hospital_add",
  components: {
    pcq
  },
  data() {
    return {
      roleLevel: "",
      addQuery: {
        hospitalName: "",
        province: "",
        city: "",
        area: "",
        address:"",
        managerName: "",
        managerId: "",
        managerPhone: "",
        managerCommissionRatio: "",
        managerLevel:'',
        deposit:''
      },
      managerId_1: 0,
      addRules: {
        hospitalName: [
          { required: true, message: "请输入医院名称", trigger: "blur" }
        ],
        agentId: [
          { required: true, message: "请选择管理员手机号", trigger: "change" }
        ],
        agentPhone: [
          { required: true, message: "请选择管理员手机号", trigger: "change" }
        ],
        province: [
          { required: true, message: "请选择省份", trigger: "change" }
        ],
        city: [
          { required: true, message: "请选择城市", trigger: "change" }
        ],
        area: [
          { required: true, message: "请选择地区", trigger: "change" }
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        deposit:[
          { required: true, message: "请输入押金金额", trigger: "blur" }
        ],
        // managerId:[
        //   { required: true, message: "请选择管理员", trigger: "blur" }
        // ]
      },
      provices: [],
      cities: [],
      areas: [],
      pId: "",
      cId: "",
      WagentList: [],
      hospitalId: this.$route.query.hospitalId,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        hospitalId: this.$route.query.hospitalId
      },
      visible:false,
      managerList:[],
      lastManagerId:'',
      nowManager:{},
      tipText:'',
      chooseLevel:0,
    };
  },
  created() {
    if (this.$route.query.roleLevel) {
      this.roleLevel = this.$route.query.roleLevel;
    }
    this.getHospitalList();
    this.provices = this.getAddressByAreaId(0);
  },
  methods: {
    toClear(type) {
      if (type == 1) {
        this.addQuery.city = "";
        this.addQuery.area = "";
      } else {
        this.addQuery.area = "";
      }
    },
    //获取管理员下拉列表 (下一级按钮触发事件)
    async getManagerList(type) {
      const len = this.managerList.length
      if(type == 1 && !this.lastManagerId){
        this.$message({
          message: '请先选择代理商',
          type: 'warning'
        });
        return
      }
      if(type == 1 && !this.managerList[len-1].managerName){
        this.$message({
          message: '请先选择代理商',
          type: 'warning'
        });
        return
      }
      var obj = type == 1 ? {managerId: this.lastManagerId} : {}
      const data = await managerList(obj);
      if(data.code == 1){
        if(data.data.length == 0){
          this.managerList[len-1].showNext = false
          this.tipText="这是最后一级了~"
          return
        }
        var _aa = {}
        _aa.list = data.data //下拉列表数据
        _aa.showNext = true // 是否有下级
        _aa.level = data.data[0].managerLevel // 代理等级
        _aa.label = _aa.level+"级代理" // 代理等级展示文字
        _aa.managerId = ''
        _aa.managerName = ''
        this.managerList.push(_aa);
      }
    },
    // 代理商下拉列表改变时触发事件
    managerChange(chooseTxt){
      const _chooseId = ''
      this.managerList.map(item => {
        item.list.map(_item => {
          if(_item.managerName == chooseTxt){
            this.lastManagerId = _item.managerId
            item.managerId = _item.managerId
            this.chooseLevel = _item.managerLevel
            if(item.list.length == 0){
              this.tipText="这是最后一级了~"
              item.showNext = false
            }else{
              this.tipText=""
              item.showNext = true
            }
            return
          }
        })
      })
      // 清掉后面的等级
      if(this.managerList.length > this.chooseLevel){
        var num = this.managerList.length - this.chooseLevel
        this.managerList.splice(1,num)
        this.tipText=""
        this.managerList.map(item => {
          item.showNext = true
        })
      }
    },
    // 选择当前代理商
    setManagerId(obj){
      if(!obj.managerName){
        this.$message({
          message: '请先选择代理商',
          type: 'warning'
        });
        return
      }
      this.nowManager.managerName = obj.managerName
      this.nowManager.managerId = obj.managerId
      this.$forceUpdate()
    },
    // 格式化选择管理员等相关数据
    clearManager(){ 
      this.nowManager = {}
      this.lastManagerId = ''
    },
    //获取医院详情
    async getHospitalList() {
      const data = await getHospitalList({
        hospitalId: this.hospitalId
      });
      if (data.code == 1) {
        this.addQuery = Object.assign({}, this.addQuery, data.data.records[0]);
        this.managerId_1 = this.addQuery.managerId;
        this.nowManager.managerName = this.addQuery.managerName
        this.nowManager.managerId = this.addQuery.managerId
        this.getManagerList();
        this.addQuery.province = getObjByName(this.addQuery.province)[0].AREA_ID;
        this.addQuery.city = getObjByName(this.addQuery.city)[0].AREA_ID;
        this.addQuery.area = getObjByName(this.addQuery.area)[0].AREA_ID;
        this.getCities();
        this.getAreas();
      }
    },
    //提交编辑医院
    submitForm() {
      if(!this.nowManager.managerId){
        this.$message({
          message: '请先选择管理员',
          type: 'warning'
        });
        return
      }
      this.$refs["addForm"].validate(async valid => {
        if (valid) {
          // console.log(this.addQuery);
          this.addQuery.hospitalAddress = this.addQuery.address
          try {
            let query = {
              hospitalId: this.hospitalId,
              hospitalName: this.addQuery.hospitalName,
              address: this.addQuery.address,
              managerId: this.nowManager.managerId,
              deposit: this.addQuery.deposit
            };
            query.province = getObjByAreaId(this.addQuery.province)[0].NAME;
            query.city = getObjByAreaId(this.addQuery.city)[0].NAME;
            query.area = getObjByAreaId(this.addQuery.area)[0].NAME;
            const res = await setHospital(query);
            if (res.code === 1) {
              this.$message.success("编辑医院成功");
              this.$router.push({
                name: "hospital_list",
                query: { hospitalId: this.hospitalId }
              });
            }
          } catch (error) {
            // console.log(error);
          }
        }
      });
    },
    //根据fid 查询省、市、区  fid = 0 查询所有省；查询市或者地区 fid 传对应的省areaID
    getAddressByAreaId(fid) {
      return getAddressByAreaId(fid);
    },
    // 获取对应市
    getCities(type) {
      if (type) {
        this.addQuery.city = "";
        this.addQuery.area = "";
      }
      this.pId = this.addQuery.province;
      this.cities = getAddressByAreaId(this.pId);
    },
    // 获取对应的地区
    getAreas(type) {
      if (type) {
        this.addQuery.area = "";
      }
      this.pId = this.addQuery.city;
      this.areas = getAddressByAreaId(this.pId);
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val;
    }
  }
};
</script>
